﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace NewsMine.DataManagers
{
    public class KeyWordManager
    {

        #region Keywork CRUD file based... 

        Dictionary<string, List<string>> keyWordDictionary = new Dictionary<string, List<string>>();


        public static string GetKeyWordFilePathAndCreateRequiredDirector(string categoryName)
        {
            string basePath = NewsMine.Configuration.ConfigurationManager.StorageBaseFolder;

            string filePath = Path.Combine(basePath, "KeyWords");
            filePath = Path.Combine(filePath, categoryName + ".txt");


            if (Directory.Exists(Path.GetDirectoryName(filePath)) == false)
            {
                Directory.CreateDirectory(Path.GetDirectoryName(filePath));
            }

            return filePath;
        }

        public static string GetKeyWordBackupFilePathAndCreateRequiredDirectory(string categoryName)
        {
            string basePath = NewsMine.Configuration.ConfigurationManager.StorageBaseFolder;

            string filePath = Path.Combine(basePath, "KeyWords");
            filePath = Path.Combine(basePath, "Backup");
            filePath = Path.Combine(filePath, categoryName + "_" + DateTime.UtcNow.Ticks.ToString() + ".txt");

            if (Directory.Exists(Path.GetDirectoryName(filePath)) == false)
            {
                Directory.CreateDirectory(Path.GetDirectoryName(filePath));
            }

            return filePath;
        }

        public static void AddKeyWordsToCategory(string categoryName, string keyword)
        {
            AddKeyWordsToCategory(categoryName, new List<string> { keyword });
        }

        public static void AddKeyWordsToCategory(string categoryName, List<string> keywords)
        {
            if (string.IsNullOrEmpty(categoryName))
                throw new ApplicationException("Invalid category name.");

            if (keywords == null)
            {
                return;
            }

            var filePath = GetKeyWordFilePathAndCreateRequiredDirector(categoryName);

            List<string> existingKeyWords = new List<string>();
            if(File.Exists(filePath))
            {
                var existingKeywordArray = File.ReadAllLines(filePath);
                if (existingKeywordArray != null)
                {
                    existingKeyWords.AddRange(existingKeywordArray);
                }
            }

            existingKeyWords.AddRange(keywords);

            existingKeyWords = existingKeyWords.Select(word => word.Trim('\r')).ToList();

            existingKeyWords = existingKeyWords.Where(word => !string.IsNullOrEmpty(word)).ToList();

            existingKeyWords = existingKeyWords.Distinct().ToList();

            if (Directory.Exists(Path.GetDirectoryName(filePath)) == false)
            {
                Directory.CreateDirectory(Path.GetDirectoryName(filePath));
            }

            File.WriteAllLines(GetKeyWordFilePathAndCreateRequiredDirector(categoryName), existingKeyWords, Encoding.UTF8);
        }

        public static void OverrideCompleteKeyWordsToCategory(string categoryName, List<string> keywords)
        {
            if (string.IsNullOrEmpty(categoryName))
                throw new ApplicationException("Invalid category name.");

            if (keywords == null)
            {
                keywords = new List<string>();
            }

            var filePath = GetKeyWordFilePathAndCreateRequiredDirector(categoryName);

            List<string> existingKeyWords = new List<string>();
            if (File.Exists(filePath))
            {
                File.Copy(filePath, GetKeyWordBackupFilePathAndCreateRequiredDirectory(categoryName)); 
            }

            existingKeyWords.AddRange(keywords);

            existingKeyWords = existingKeyWords.Select(word => word.Trim('\r')).ToList();

            existingKeyWords = existingKeyWords.Where(word => !string.IsNullOrEmpty(word)).ToList();

            existingKeyWords = existingKeyWords.Distinct().ToList();

            File.WriteAllLines(GetKeyWordFilePathAndCreateRequiredDirector(categoryName), existingKeyWords, Encoding.UTF8);
        }

        public static void DeleteKeyWordCategory(string categoryName)
        {
            var filePath = GetKeyWordFilePathAndCreateRequiredDirector(categoryName);

            if (File.Exists(filePath))
            {
                File.Copy(filePath, GetKeyWordBackupFilePathAndCreateRequiredDirectory(categoryName));
                File.Delete(filePath);
            }


        }

        public static List<string> GetAllKeywordsByCategory(string categoryName)
        {
            string filePath = GetKeyWordFilePathAndCreateRequiredDirector(categoryName);

            if (File.Exists(filePath) == false)
            {
                return new List<string>();
            }

            string[] keywords = File.ReadAllLines(filePath);

            List<string> results = new List<string>();

            if (keywords != null)
            {
                results = new List<string>(keywords);

                return results.OrderBy(q => q).ToList();
            }
            else
                return new List<string>();
        }

        public static List<string> GetAllCategories()
        {
            string folderPath = Path.GetDirectoryName(GetKeyWordFilePathAndCreateRequiredDirector("dkdk"));

            string[] files = Directory.GetFiles(folderPath);

            var resultedCategories = new List<string>();

            if (files != null)
            {
                resultedCategories = files.Select(word => Path.GetFileNameWithoutExtension(word)).ToList();
            }

            return resultedCategories;
        }

        #endregion


        public bool IsStopWord(string word)
        {
            return false;
        }


        static List<string> domainsNotSupportsIframe = new List<string>();

        public static List<string> GetDomainsForNotIframeAndRedict()
        {
            if (domainsNotSupportsIframe == null || domainsNotSupportsIframe.Count == 0)
            {
                domainsNotSupportsIframe.Add("youtube".ToLower()); // make sure we are adding lower case.
                domainsNotSupportsIframe.Add("dnaindia".ToLower()); // make sure we are adding lower case.
            }

            return domainsNotSupportsIframe;
        }

        public static bool IsDomainSupportsIframe(string domain)
        {
            if (string.IsNullOrEmpty(domain))
                return true;

            domain = domain.ToLower();

            bool result = true;
            foreach (var item in GetDomainsForNotIframeAndRedict())
            {
                if (domain.Contains(item) || item.Contains(domain))
                {
                    result = false;
                    break;
                }
            }

            return result;
        }


      
    }
}
